package com.fresher.controller;

import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.fresher.model.Accountinfo;
import com.fresher.model.Log;
import com.fresher.model.UserRole;
import com.fresher.service.AccountService;
import com.fresher.service.UserService;
import com.fresher.service.LogService;

@Controller
public class MainController {

	@Autowired
	MessageSource messageSource;

	@Autowired
	AccountService accountService;

	@Autowired
	UserService userService;

	@Autowired
	LogService logService;

	@RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
	public ModelAndView login(Locale locale,
			@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout) {

		ModelAndView model = new ModelAndView();
		if (error != null) {
			String message = messageSource.getMessage(
					"label.invalidAuthentication", null, locale).toString();
			model.addObject("error", message);
			System.out.println(locale.toLanguageTag());

		}
		if (logout != null) {
			model.addObject("msg", messageSource.getMessage("label.logoutSuccess", null, locale).toString());
		}
		model.setViewName("login");
		return model;

	}

	// for 403 access denied page
	@RequestMapping(value = "/403", method = RequestMethod.GET)
	public ModelAndView accesssDenied() {

		ModelAndView model = new ModelAndView();

		// check if user is login
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (!(auth instanceof AnonymousAuthenticationToken)) {
			UserDetails userDetail = (UserDetails) auth.getPrincipal();
			System.out.println(userDetail);
			model.addObject("username", userDetail.getUsername());
		}
		model.setViewName("403");
		return model;
	}

	@RequestMapping(value = "/changepassword", method = RequestMethod.GET)
	public ModelAndView changePasswordPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("changepassword");
		return model;
	}

	// process change password

	@RequestMapping(value = "/processchangepassword", method = RequestMethod.POST)
	public ModelAndView processchangepassword(HttpServletRequest request,
			Model model) throws ParseException {

		ModelAndView model1 = new ModelAndView();
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		UserDetails userDetail = (UserDetails) auth.getPrincipal();
		String currentPassword = userDetail.getPassword();
		String loginId = userDetail.getUsername();

		String oldPassord, newPassword, confirmPassword;

		oldPassord = request.getParameter("oldPassword");
		newPassword = request.getParameter("newPassword");
		confirmPassword = request.getParameter("confirmPassword");

		String mess = userService.changeUserPassword(loginId, currentPassword,
				oldPassord, newPassword, confirmPassword);
		model1.addObject("mess", mess);
		model1.setViewName("changepassword");

		return model1;
	}

	@RequestMapping(value = "/adminManage", method = RequestMethod.GET)
	public ModelAndView admin() {
		ModelAndView model = new ModelAndView();
		List<Log> logList = logService.getListLogs();
		model.addObject("logList", logList);
		model.setViewName("adminManage");
		return model;
	}

	@RequestMapping(value = "/accountinfo", method = RequestMethod.GET)
	public ModelAndView AccountInfoPage() {

		ModelAndView model = new ModelAndView();
		String loginId = userService.getLoggedUserName();
		List<Accountinfo> accountList = accountService.getListAccount(loginId);
		model.addObject("listAccount", accountList);
		model.setViewName("AccountInfo");
		return model;
	}

	// get admin user list
	@RequestMapping(value = "/userlist", method = RequestMethod.GET)
	public ModelAndView AdminGetCreateNewUser() {
		ModelAndView model = new ModelAndView();
		List<UserRole> listRole = userService.getUserRoleList();
		model.addObject("listRole", listRole);
		model.setViewName("userlist");
		return model;
	}

	// create new user
	@RequestMapping(value = "/createNewUser", method = RequestMethod.POST)
	public String AdminCreateNewUser(HttpServletRequest request, Model model,
			RedirectAttributes rdtt) {
		String username, password, role;
		// ModelAndView model = new ModelAndView();
		username = request.getParameter("txtUsername");
		password = request.getParameter("txtPassword");
		role = request.getParameter("cbAdmin");
		String mess = userService.createNewuser(username, password, role);
		// model.addAttribute("mess", mess);
		rdtt.addFlashAttribute("mess", mess);
		// model.setViewName("userlist");

		return "redirect:userlist";

	}

	@RequestMapping(value = "/usernameCheck", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public @ResponseBody String checkUsername(@RequestParam String name) {
		Locale locale = LocaleContextHolder.getLocale();
		String result = "";
		boolean isOk;
		
		if (name != "") {
			isOk = userService.checkUsername(name);
			if (isOk == true) {
				result = messageSource.getMessage("label.nameTaken", null,
						locale).toString();
			} else {
				result = messageSource.getMessage("label.nameOK", null, locale)
						.toString();
			}
		}
		return result;
	}

}